<?php
/**
 * Yotaku
 * @author Creatint<creatint@163.com>
 * @copyright www.yotaku.cn 2016
 */
namespace Addons\System;
use Common\Controller\Addon;

class SystemAddon extends Addon{

    //系统登录
    public function login($params=array('direct'=>false,'openid'=>'')){
        trace('系统登录插件');
//        dump("系统登录插件");
        // 登录成功的跳转页面 url均需编码传递
        $acturl = I('acturl',$_SERVER['PHP_SELF'],'strip_tags');

        //获取uid
        $uid = session("member.id");
        //是否存在UID
        if($uid>0){
            return $uid;
        }else{

            //未登录，跳转登录界面 url编码传递
            redirect(U('Login/index',array('acturl'=>urlencode($acturl),'openid'=>$params['openid'])));
        }
    }

//    //订单处理 如检测库存
//    public function confirm($post){
//        echo '接收到的参数：';dump($post);
//        //对商品库存检测
//        if(!empty($post['cart_id']) && is_array($post['cart_id'])){
//            //购物车
//        } elseif($post['goods_id']>0 && $post['number']) {
//
//        }
//        $Goods = D("Home/Goods");
//
//        die();
//    }



//  订单处理插件
    public function order($cart_id){
//        echo '购物车IDs:';dump($cart_id);
        $Cart = D("Cart");
        $Goods = D("Goods");
        $carts = $Cart->getCartsById($cart_id);


        $over = false;
        $over_goods = '以下商品数量超出了库存<br> ';
        foreach($carts as $cart){
            $goods = $Goods->getDetail($cart['goods_id'],'stock');
//            dump($goods);
            if($cart['number'] > $goods['stock']){
//                echo '购买数量超过库存';
                //return '购买数量超过库存';
                $over_goods .= $cart['title'].":{$cart['number']}>{$goods['stock']}<br>";
                $over = true;
            }
        }unset($cart);
        //是否超出库存
        if($over){
            $this->alert($over_goods,U("Cart/index"));
        }
        //未超出,减少库存
        foreach($carts as $cart){
            0==$cart['dec_status'] && ($Goods->where("id={$cart['goods_id']}")->setDec('stock',$cart['number']) && $Cart->where("id={$cart['id']}")->setInc('dec_status',1) && $Goods->where("id={$cart['goods_id']}")->setInc('sales',$cart['number']));
        }unset($cart);
 
    }

    // 订单数据过滤
    public function confirm($post){
        return $post;
    }


    /**
     * 提示跳转
     */
    public function alert($msg,$url) {
        $this->assign('info',array('msg'=>$msg,'url'=>$url));
        $this->display(T('Home@Notice/location'));
    }
    public function install(){
        return true;
    }

    public function uninstall(){
        return true;
    }
}